#!/bin/bash
# cci_task_gz
# root_passwd
# grub_passwd
# upload_image_dir 
# image_config_kernel

. $LKP_SRC/lib/http.sh
. $LKP_SRC/lib/upload.sh
. $LKP_SRC/lib/debug.sh

config_env_repos()
{
	rm -rf /etc/yum.repos.d.bak
	mv /etc/yum.repos.d /etc/yum.repos.d.bak
	mkdir -p /etc/yum.repos.d
	local my_repo="/etc/yum.repos.d/my.repo"
	i=1
	for repo in ${env_repos[@]}
	do
		cat >> ${my_repo} <<-EOF
		[my_repo_$i]
		name=my_repo_$i
		baseurl=${repo}
		enabled=1
		gpgcheck=0
		priority=$i

		EOF
		let i=i+1
	done
}

init_env()
{
	export LANG=en_US.UTF-8
	custom_dir=/tmp/cfg_openEuler
	tailor_dir=/opt/imageTailor
	if [ "$image_type" == "iso" ]; then
		cfg_dir=${tailor_dir}/custom/cfg_openEuler
	elif [ "$image_type" == "cpio" ]; then
		cfg_dir=${tailor_dir}/custom/cfg_EMB_rootfs
	elif [ "$image_type" == "docker" ]; then
		cfg_dir=${tailor_dir}/custom/cfg_docker
	else
		die "the image type ${image_type} can't support now."
	fi
	cur_docker_config=${cfg_dir}/config.xml
	cur_rpm=${cfg_dir}/rpm.conf
	new_rpm=${custom_dir}/rpm.conf
	cur_cmd=${cfg_dir}/cmd.conf
	new_cmd=${custom_dir}/cmd.conf
	cur_sys=${cfg_dir}/sys.conf
	new_sys=${custom_dir}/sys.conf
	euler_base=/opt/imageTailor/repos/euler_base/
	tmp_file=/tmp/_tmp
	result=/opt/imageTailor/result

	config_env_repos
}

config_customs_repos()
{
	rm -rf /etc/yum.repos.d.bak
	mv /etc/yum.repos.d /etc/yum.repos.d.bak
	mkdir -p /etc/yum.repos.d
	local my_repo="/etc/yum.repos.d/my.repo"
	i=1
	for repo in ${custom_repos[@]}
	do
		cat >> ${my_repo} <<-EOF
		[my_repo_$i]
		name=my_repo_$i
		baseurl=${repo}
		enabled=1
		gpgcheck=0
		priority=$i

		EOF
		let i=i+1
	done
}

init_image_tailor()
{
	yum remove -y imageTailor
	yum install -y imageTailor expect passwd createrepo cpio dos2unix grub2-tools-minimal pigz || die "init image tailor install rpms error."
	# run imageTailor in docker
	sed -i "s/'-D',//g" /usr/lib/python3.9/site-packages/kiwi/system/setup.py || die "init image tailor sed kiwi error."

	mkdir -p "${euler_base}"

	config_customs_repos
}

get_image_config()
{
	local cci_http_host=${INITRD_HTTP_HOST}
	local cci_http_port=${INITRD_HTTP_PORT:-8800}	
	local remote_dir="http://${cci_http_host}:${cci_http_port}${cci_task_gz}"
	[[ "$is_remote" == "true"  ]] && {
		remote_dir="${INITRD_HTTP_HOST}:${INITRD_HTTP_PORT}{cci_task_gz}"
	}
	http_get_file "${remote_dir}" "${cci_task_gz}" || die "get custom cfg failed."
	tar -xvf "${cci_task_gz}" -C /tmp/ || die "tar custom cfg failed."
}

init_cfg()
{
	# xmllint need a standard xml file
	cfgs=(${new_rpm} ${new_cmd})	
	for cfg in ${cfgs[@]}
	do
		[ ! -f "$cfg" ] && continue
		sed -i '1i <image>' ${cfg}
		sed -i '$a </image>' ${cfg}
	done
}

parse_drivers()
{
	[ ! -f "$new_rpm" ] && return
	xmllint --xpath "//drivers/node()" ${new_rpm} | sed '/^ *$/d' > ${tmp_file}
	while read line
	do
		grep -q \'${line}\' ${cur_rpm} || {
			sed -i "<drivers>/a\        ${line}" ${cur_rpm}
		}
	done < ${tmp_file}
}

parse_add_packages()
{
	[ ! -f "$new_rpm" ] && return
	xmllint --xpath "//packages[@patternType='plusRecommended']/node()" ${new_rpm} | sed '/^ *$/d' > ${tmp_file}
	while read line
	do
		grep -q \'${line}\' ${cur_rpm} || {
			sed -i "/<packages type=\"bootstrap\" patternType=\"plusRecommended\">/a\        ${line}" ${cur_rpm}
		}
	done < ${tmp_file}
}

parse_del_packages()
{
	[ ! -f "$new_rpm" ] && return
	xmllint --xpath "//packages[@type='delete']/node()" ${new_rpm} | sed '/^ *$/d' > ${tmp_file}
	while read line
	do
		grep -q \'${line}\' ${cur_rpm} || {
			sed -i "/<packages type=\"delete\">/a\        ${line}" ${cur_rpm}
		}
	done < ${tmp_file}
}

parse_del_files()
{
	[ ! -f "$new_cmd" ] && return
	xmllint --xpath "//strip[@type='delete']/node()" ${new_cmd} | sed '/^ *$/d' > ${tmp_file}
	while read line
	do
		grep -q \'${line}\' ${cur_cmd} || {
			sed -i "/<strip type=\"delete\">/a\        ${line}" ${cur_cmd}
		}
	done < ${tmp_file}
}

parse_add_tools()
{
	[ ! -f "$new_cmd" ] && return
	xmllint --xpath "//strip[@type='tools']/node()" ${new_cmd} | sed '/^ *$/d' > ${tmp_file}
	while read line
	do
		grep -q \'${line}\' ${cur_cmd} || {
			sed -i "/<file name=\"[\"\/>/a\        ${line}" ${cur_cmd}
		}
	done < ${tmp_file}
}

parse_sys()
{
	[ ! -f "$new_sys" ] && return
        local t1=$1
        local t2=$2
        local start1=$(sed -n -e "/${t1}/=" ${new_sys})
        local end1=$(sed -n -e "/${t2}/=" ${new_sys})
        [ -n "$start1" ] || return

        sed -n "$((${start1} + 1)), $((${end1} - 1))p" ${new_sys} > ${tmp_file}

        local start2=$(sed -n -e "/${t1}/=" ${cur_sys})
        local end2=$(sed -n -e "/${t2}/=" ${cur_sys})
        sed -i "$((${start2} + 1)),$((${end2} - 1))d" ${cur_sys}

        while read line
        do
                sed -i "/${t1}/a\\${line}" ${cur_sys}
        done < ${tmp_file}
}

add_files()
{
	[ "$image_type" == "iso" ] && {
		[ -d "$custom_dir/usr_file" ] && {
			cp -r ${custom_dir}/usr_file/* ${cfg_dir}/usr_file
		}
	}

	[ -d "$custom_dir/usr_install/hook" ] && {
		cp -r ${custom_dir}/usr_install/hook/* ${cfg_dir}/usr_install/hook
	}
}

download_rpms()
{
	rm -rf ${euler_base}/*.rpm
	yumdownloader kernel grub2-efi shim --downloaddir="${euler_base}"
}

set_root_passwd()
{
	userdel -r testUser
	useradd testUser
	expect <<-EOF
	spawn passwd testUser
	expect {
		"*password"
		{send ${root_passwd}\r;exp_continue}
		"*password"
		{send ${root_passwd}\r;exp_continue}
	}
	expect eof
	EOF
	local new_root_passwd=$(cat /etc/shadow|grep testUser|awk -F ':' '{print $2}')
	sed -i "s|pwd=\"\"|pwd=\"${new_root_passwd}\"|g" ${cur_rpm}
	sed -i "s|pwd=\"\"|pwd=\"${new_root_passwd}\"|g" ${tailor_dir}/kiwi/minios/cfg_minios/rpm.conf
	#sed -i "s|sys_cut='yes'|sys_cut='no'|g" /opt/imageTailor/kiwi/minios/cfg_minios/sys.conf
}

set_grub_passwd()
{
	[[ "$image_type" != "iso" ]] && return

	expect <<-EOF
	spawn grub2-set-password -o /tmp/
	expect {
		"*password"
		{send ${grub_passwd}\r;exp_continue}
		"*password"
		{send ${grub_passwd}\r;exp_continue}
	}
	expect eof
	EOF

	cat /tmp/user.cfg | awk -F '=' '{printf("%s=\"%s\"",$1,$2)}' >> ${cfg_dir}/usr_file/etc/default/grub
	sed -i 's/GRUB2_PASSWORD=/GRUB_PASSWORD=/g' ${cfg_dir}/usr_file/etc/default/grub
}

set_kernel_params()
{
	sed -i '/GRUB_CMDLINE_LINUX=/d' ${cfg_dir}/usr_file/etc/default/grub	
	sed -i "1 i GRUB_CMDLINE_LINUX=\"${image_config_kernel}\"" ${cfg_dir}/usr_file/etc/default/grub
	dos2unix ${cfg_dir}/usr_file/etc/default/grub
}


tailor_image()
{
	rm -rf ${result}
	cd ${tailor_dir}
	repo_urls=(${custom_repos})
	echo ${repo_urls[0]}
	chmod 777 mkdliso
	cat mkdliso|grep 'source path='
	if [ "$image_type" == "docker" ];then
		sed -i "s|<source path=.*|<source path=\"${repo_urls[0]}\"/> </repository>|" ${cur_docker_config}
	else
		sed -i "s|<source path=.*|<source path=\"${repo_urls[0]}\"/>|" mkdliso
	fi

	cat mkdliso|grep 'source path='
	if [ "$image_type" == "cpio" ];then
		./mkdliso -p EMB_rootfs -c custom/cfg_EMB_rootfs || die "tailor image cpio failed."
	elif [ "$image_type" == "iso" ];then
		./mkdliso -p openEuler -c custom/cfg_openEuler --minios force || die "tailor image iso failed."
	elif [ "$image_type" == "docker" ];then
		sed -i '/yum remove -y/d' custom/cfg_docker/images.sh
		sed -i '/rpm -e --nodeps/d' custom/cfg_docker/images.sh
		./mkdliso -p docker -c custom/cfg_docker || die "tailor image docker failed."
	fi
}

check_build_result()
{
	res=$(find /opt/imageTailor/result -type f -name "*iso*" -o -name "*docker*" -o -name "*cpio*")
	[ -z "$res" ] && die "can't find the build result"
	[ "$?" != "0" ] && exit 0
}

upload_result()
{
	local log_dir=/opt/imageTailor/result/log
	for one in $(ls ${log_dir})
	do
		upload_one_curl ${log_dir}/${one}  ${upload_image_dir}
	done

	for one in $(find /opt/imageTailor/result -type f -name "*iso*" -o -name "*docker*" -o -name "*cpio*")
	do
		upload_one_curl ${one} ${upload_image_dir} || die "upload ${one} to ${upload_image_dir} error."
	done
}


build_non_docker()
{
	[[ "$image_type" == "docker" ]] && return
	get_image_config
	init_cfg
	parse_drivers
	parse_add_packages
	parse_del_packages
	parse_del_files
	parse_add_tools
	parse_sys '<HDpartitions>' '<\/HDpartitions>'
	parse_sys '<sysconfig>' '<\/sysconfig>'
	parse_sys '<netconfig-0>' '<\/netconfig-0>'
	add_files
	download_rpms
	set_root_passwd
	set_grub_passwd
	set_kernel_params
}

parse_docker_packages()
{
	[[ "$image_type" != "docker" ]] && return
	[ ! -f "$new_rpm" ] && return
	xmllint --xpath "//packages[@patternType='plusRecommended']/node()" ${new_rpm} | sed '/^ *$/d' > ${tmp_file}
	cat ${tmp_file}
	while read line
	do
		echo ${line}
		echo ${cur_docker_config}
		grep -q \'${line}\' ${cur_docker_config} || {
			sed -i "/<packages type=\"image\">/a\        ${line%\.*}\"\/>" ${cur_docker_config}
		}
	done < ${tmp_file}

	cat ${cur_docker_config}
}

build_docker()
{
	[[ "$image_type" != "docker" ]] && return
	get_image_config
	init_cfg
	parse_docker_packages
}

init_env
config_env_repos
init_image_tailor
build_non_docker
build_docker
tailor_image
upload_result
check_build_result
